package com.fate.controller;

import com.fate.anno.Log;
import com.fate.domain.SysMenu;
import com.fate.mapper.SysMenuMapper;
import com.fate.service.SysMenuService;
import com.fate.vo.MenuAuthsVo;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
@Api(tags = "后台菜单管理的接口")
@RequestMapping("sys/menu")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询菜单和权限的连接口
     */
    @GetMapping("nav")
    @ApiResponse(code=200,message="连接成功",response = MenuAuthsVo.class)
    @ApiOperation(value = "查询菜单和权限的连接口")
    @Log(operation = "查询菜单和权限的接口")
    public ResponseEntity<MenuAuthsVo> menuList(){
        //获取当前用户
        String sysUserId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        // 1.根据用户id查菜单
        List<SysMenu> menus =  sysMenuService.findUserMenu(Long.valueOf(sysUserId));
        // 2.查权限 不需要查
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        List<String> auths = new ArrayList<>(authorities.size() * 2);
        // 转一下权限
        authorities.forEach(auth->auths.add(auth.getAuthority()));
        // 3.封装结果
        MenuAuthsVo menuAuthsVo = new MenuAuthsVo();
        menuAuthsVo.setMenuList(menus);
        menuAuthsVo.setAuthorities(auths);
        // 4.返回
        return ResponseEntity.ok(menuAuthsVo);
    }
}
